/**
 * 版权所有 2009-2012山东新北洋信息技术股份有限公司
 * 保留所有权利。
 */
package com.linyaonan.leetcode.easy._110;

/**
 * @ProjectName: leetcode
 * @Package: com.linyaonan.leetcode.easy._110
 * @ClassName: BalancedTree
 * @Author: linyaonan
 * @Date: 2019/11/4 10:30
 */
public class BalancedTree {

    public boolean isBalanced(TreeNode root) {
        // 空节点直接返回
        if (root == null) {
            return true;
        }
        try {
            getNodeHeight(root, 0);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private int getNodeHeight(TreeNode node, int count) throws Exception {
        if (node == null) {
            return count;
        }
        ++count;
        int leftCount = getNodeHeight(node.left, count);
        int rightCount = getNodeHeight(node.right, count);
        if (Math.abs(leftCount - rightCount) > 1) {
            throw new Exception("got it");
        }
        return Math.max(leftCount, rightCount);
    }

}
